package cn.com.guage.dtm.check.datasource.config;

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import cn.com.guage.dtm.check.datasource.aop.DataSourceType;
import cn.com.guage.dtm.check.datasource.aop.DynamicDataSource;

/**
 * 数据源配置
 * @author yangdechao
 *
 */
@Configuration
@MapperScan(basePackages = "cn.com.guage.dtm.check.mapper", sqlSessionFactoryRef = "sqlSessionFactory")
public class DataSourceConfig {
	@Primary
	@Bean(name = "dataSourceDB01")
	@ConfigurationProperties(prefix = "spring.datasource.db1")
	public DataSource getDateSourceDB01() {
		return DataSourceBuilder.create().build();
	}

	@Bean(name = "dataSourceDB02")
	@ConfigurationProperties(prefix = "spring.datasource.db2")
	public DataSource getDateSourceDB02() {
		return DataSourceBuilder.create().build();
	}

	@Bean(name = "dynamicDataSource")
	public DynamicDataSource getDynamicDataSource(@Qualifier("dataSourceDB01") DataSource test1DataSource,
			@Qualifier("dataSourceDB02") DataSource test2DataSource) {
		Map<Object, Object> targetDataSource = new HashMap<>();
		targetDataSource.put(DataSourceType.DataBaseType.DB01, test1DataSource);
		targetDataSource.put(DataSourceType.DataBaseType.DB02, test2DataSource);
		DynamicDataSource dataSource = new DynamicDataSource();
		dataSource.setTargetDataSources(targetDataSource);
		dataSource.setDefaultTargetDataSource(test1DataSource);
		return dataSource;
	}

	@Bean(name = "sqlSessionFactory")
	public SqlSessionFactory getSqlSessionFactory(@Qualifier("dynamicDataSource") DataSource dynamicDataSource)
			throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dynamicDataSource);
		bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/*.xml"));
		return bean.getObject();
	}

}
